﻿using System.Globalization;
using System.IO;
using System.Web.UI;
using Quiki.ExpressionParsers;
using Quiki.Templates;

namespace Quiki
{
    public class HtmlFormatter
    {
        public HtmlFormatter (TemplatesRegistry templatesRegistry)
        {
            this.templatesRegistry = templatesRegistry;
        }

        public DocumentGraph DocumentGraph
        {
            get { return documentGraph; }
            set { documentGraph = value; }
        }

        public WikiDocument Document
        {
            get { return document; }
            set { document = value; }
        }

        public string Format (WikiTextElement rootElement)
        {
            this.rootElement = rootElement;

            StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture);
            using (writer = new XhtmlTextWriter (stringWriter))
            {
                context = new HtmlFormatterContext (writer, templatesRegistry);
                context.Document = document;
                context.DocumentGraph = documentGraph;
                Process ();
            }

            return stringWriter.ToString();
        }

        private void Process()
        {
            context.ProcessElement(rootElement);
            context.CloseAllParagraphs();
        }

        private HtmlFormatterContext context;
        private WikiDocument document;
        private DocumentGraph documentGraph;
        private WikiTextElement rootElement;
        private readonly TemplatesRegistry templatesRegistry;
        private XhtmlTextWriter writer;
    }
}
